package processes

import (
	"encoding/json"
	"fmt"
	"go_code/project01_basic/chapter15_qq/message"
	"go_code/project01_basic/chapter15_qq/server/model"
	"go_code/project01_basic/chapter15_qq/server/utils"
)

type SmsProcess struct {
}

func (s *SmsProcess) SeverProcessGroupSms(mes *message.Message) (err error) {
	//解析消息
	var smsMes message.SmsMes
	err = json.Unmarshal([]byte(mes.Data), &smsMes)
	if err != nil {
		fmt.Println("json.Unmarshal err=", err)
		return
	}

	//群发消息
	for id, up := range AllUsers.Users {
		if id == smsMes.UserId {
			continue
		}
		if up.UserStatus == message.UserOffline {
			err = model.MyUserDao.LeaveSmsSave(mes, up.UserId)
		} else {
			//传递信息
			tf := &utils.Transfer{
				Conn: up.Conn,
			}
			err = tf.Delivery(mes)
			if err != nil {
				fmt.Println("Delivery smsMes err=", err)
				return
			}
		}
	}
	return
}

func (s *SmsProcess) SeverProcessPrivateSms(mes *message.Message) (err error) {
	//解析消息
	var smsPrivateMes message.SmsPrivateMes
	err = json.Unmarshal([]byte(mes.Data), &smsPrivateMes)
	if err != nil {
		fmt.Println("json.Unmarshal err=", err)
		return
	}

	//私发消息
	for id, up := range AllUsers.Users {
		if id == smsPrivateMes.DstUser {
			//离线存储信息，在线转发信息
			if up.UserStatus == message.UserOffline {
				err = model.MyUserDao.LeaveSmsSave(mes, up.UserId)
			} else {
				tf := &utils.Transfer{
					Conn: up.Conn,
				}
				err = tf.Delivery(mes)
				if err != nil {
					fmt.Println("Delivery smsPrivateMes err=", err)
					return
				}
			}
		}
	}
	return
}
